package com.peng.aidlcommunicationdemo;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int MESSAGE_NEW_BOOK_ARRIVED = 1;

    private IBookManager remoteBookManager;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_NEW_BOOK_ARRIVED:
                    Log.d(TAG, "handleMessage: receive new book:" + msg.obj);
                default:
                    super.handleMessage(msg);
            }
        }
    };

    /**
     * onNewBookArrived 运行于客户端的 Binder 线程池，通过使用Handler，将数据抛出去
     */
    private IOnNewBookArrivedListener mOnNewBookArrivedListener = new IOnNewBookArrivedListener.Stub() {
        @Override
        public void onNewBookArrived(Book book) throws RemoteException {
            mHandler.obtainMessage(MESSAGE_NEW_BOOK_ARRIVED, book).sendToTarget();
        }
    };

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            // 获取服务端的代理，可以通过该代理，调用服务端的方法
            IBookManager iBookManager = IBookManager.Stub.asInterface(iBinder);
            try {
                remoteBookManager = iBookManager;
                List<Book> list = iBookManager.getBookList();
                Log.i(TAG, "onServiceConnected: query book list,list type:" + list.getClass().getCanonicalName());
                Log.i(TAG, "onServiceConnected: query book list:" + list.toString());
                Book book = new Book(3, "Android 开发艺术探索");
                iBookManager.addBook(book);
                Log.i(TAG, "onServiceConnected: add book:" + book);
                List<Book> newList = iBookManager.getBookList();
                Log.i(TAG, "onServiceConnected: query book list:" + newList.toString());

                // 注册监听器到另一个进程，
                // 注册，就是将该类添加到另一个进程的 RemoteCallbackList 集合中
                // 当另一个进程发生变化时，就通过传递过去的对象，远程调用客户端的方法
                // 此时，客户端的方法运行在客户端的Binder线程池中。在客户端中，需要实现AIDL接口。
                iBookManager.registerListener(mOnNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            remoteBookManager = null;
            Log.d(TAG, "onServiceDisconnected: binder died");
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(this, BookManagerService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (remoteBookManager != null && remoteBookManager.asBinder().isBinderAlive()) {
            Log.i(TAG, "onDestroy: unregister listener:" + mOnNewBookArrivedListener);
            try {
                remoteBookManager.unregisterListener(mOnNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindService(serviceConnection);
    }
}
